package vn.com.shoppie.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

public class SUtilBitmap {
	private static SUtilBitmap _instance = new SUtilBitmap();

	public static SUtilBitmap getInstance() {
		return _instance;
	}

	// get Link Image
	// get Image from CACHE
	// if not have
	// get Image from sdCard
	// if have: return
	// if not have: download Image from network
	// if download success
	// save Image to sdCard
	// get Image from sdCard
	// if download not success
	// return null

	private static HashMap<String, Bitmap> CACHE_BITMAP = new HashMap<String, Bitmap>();
	private int sizePoolCache=50;

	// PROCESS BITMAP - LINK
	public Bitmap getBitmap(Context context, String link) {
		if (CACHE_BITMAP.containsKey(link)) {
			return CACHE_BITMAP.get(link);
		}
		Bitmap result = null;
		result = getBitmapLocal(context, link);
		if (result != null) {
			CACHE_BITMAP.put(link, result);
		}
		if(CACHE_BITMAP.size()>sizePoolCache){
			CACHE_BITMAP.clear();
		}
		return result;
	}

	public String linkToMemory(String link) {
		Log.e("DOWNLOAD IMAGE", "Link: " + link);
		String filePath = "";
		File file = new File(linkToPath(link));
		//Log.e("full link", linkToPath(link));
		try {
			URL url = new URL(link);
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.connect();

			if (!file.isFile()) {
				file.createNewFile();
			}
			InputStream in = new java.net.URL(link).openStream();
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
            byte[] bitmapdata = bos.toByteArray();

            //write the bytes in file
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bitmapdata);
            
            if(bitmap!=null) return file.getAbsolutePath();
            
			FileOutputStream fileOutput = new FileOutputStream(file);
			InputStream inputStream = urlConnection.getInputStream();
			int totalSize = urlConnection.getContentLength();
			int downloadedSize = 0;
			byte[] buffer = new byte[1024];
			int bufferLength = 0;
			while ((bufferLength = inputStream.read(buffer)) > 0) {
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
				// Log.i("Progress:", "downloadedSize:" + downloadedSize
				// + "totalSize:" + totalSize);
			}
			fileOutput.close();
			if (downloadedSize == totalSize)
				filePath = file.getPath();
		} catch (MalformedURLException e) {
			filePath = null;
			file.delete();
		} catch (IOException e) {
			filePath = null;
			file.delete();
		}
		return filePath;
	}

	public String bitmapToFile(Bitmap bitmap, String link) throws IOException {
		String nameBitmap = encodeLink(link);
		String writeTo = new File(Environment.getExternalStorageDirectory()
				+ File.separator + nameBitmap).toString();
		FileOutputStream output;
		output = new FileOutputStream(writeTo);
		bitmap.compress(Bitmap.CompressFormat.PNG, 0, output);
		output.close();
		return nameBitmap;
	}

	public Bitmap getBitmapLocal(Context context, String link) {
		String path = linkToPath(link);
		try {
			return pathLocalToBitmap(path);
		} catch (FileNotFoundException e) {
			String pathImage = linkToMemory(link);
			if (pathImage != null && !pathImage.equals("")) {
				return null;
			} else {
				return null;
			}
		} catch (IOException e) {
			String pathImage = linkToMemory(link);
			if (pathImage != null && !pathImage.equals("")) {
				return null;
			} else {
				return null;
			}
		}
	}

	public Bitmap fileToBitmap(File f) throws IOException {
		FileInputStream fis = new FileInputStream(f);
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 2; // try to decrease decoded image
		options.inPurgeable = true; // if necessary purge pixels into
									// disk
		options.inScaled = true; // scale down image to actual device
									// density
		Bitmap result = BitmapFactory.decodeStream(fis, null, options);
		fis.close();
		return result;
	}

	public Bitmap pathLocalToBitmap(String path) throws IOException {
		File f = new File(path);
		return fileToBitmap(f);
	}

	public String linkToPath(String link) {
		
		File SDCardRoot = Environment.getExternalStorageDirectory()
				.getAbsoluteFile();
		File folderApp=new File(SDCardRoot.getAbsolutePath(),"/shoppie/cache/img" );
		if(!folderApp.exists()){
			if(!folderApp.isDirectory()){
				boolean success=folderApp.mkdirs();
				if(!success){
					Log.e("create folder app", "Failed");
				}
			}
		}
		String filename = folderApp.getAbsolutePath() + File.separator + encodeLink(link);
		// File file = new File(SDCardRoot, filename);
		// return file.getAbsolutePath();
		return filename;
	}

	// PROCESS BASE64
	public String encodeLink(String link) {
		// http://web.shoppie.com.vn:8080/Upload/MERCHANTS/8/CAMPAIGNS/cp.jpg
		link = link.replaceAll("http://web.shoppie.com.vn:8080/", "%22");
		link = link.replaceAll("/", "%21");
		link = link.replaceAll(" ", "%20");
		link = link.replaceAll(":", "%20");
		return link;
	}

	public String decodeLink(String base64) {
		return Base64.decode(base64, Base64.URL_SAFE).toString();
	}
}
